﻿
namespace SistemaLogistica.Windows.Forms.Telefonia.Operaciones
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.EventArgs;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Entities.Types;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfEntregaTelefono : MaestroDetalleSeguro, Observador
    {
        public CwfEntregaTelefono()
        {
            InitializeComponent();
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                this.MaestroBindingSource.DataSource = AsignacionManager.Instancia.Buscar(this.dtpDesde.Value, this.dtpHasta.Value, (int)PedidoType.Telefono);
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void cmbNotaSalida_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbNotaSalida.SelectedValue != null)
            {
                NotaSalida notaSalida = NotaSalidaManager.Instancia.ObtenerPorID(Convert.ToInt32(this.cmbNotaSalida.SelectedValue));
                this.lblNotaSalida.Text = "Nota de Salida realizada el " + notaSalida.Fecha.ToLongDateString();

                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleNotaSalida d in notaSalida.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = string.Empty;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = 0;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = Convert.ToInt32(d.Cantidad);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[3].Value = string.Empty;
                }
            }
        }

        private void DgvDetalle_BeforeShowControl(object sender, BeforeShowControlEventArg e)
        {
            switch (e.Cell.ColumnIndex)
            {
                case 0: // Cargar Empleados
                    try
                    {
                        ComboBox cmbA = e.Control as ComboBox;
                        cmbA.DataSource = null;
                        cmbA.DisplayMember = "ToString";
                        cmbA.ValueMember = "IdEmpleado";
                        cmbA.DataSource = EmpleadoManager.Instancia.Listar();
                    }
                    catch (Exception ex)
                    {
                        Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
                    }
                    break;
                default:
                    break;
            }
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            Asignacion asignacion = this.MaestroBindingSource[e.RowIndex] as Asignacion;

            if (asignacion != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);

                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "Nº: " + asignacion.IdAsignacion.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "Nº: " + asignacion.IdAsignacion.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 8);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, "Nº Nota Salida: " + asignacion.NotaSalida.IdNotaSalida.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
                else
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);
                    if (selected)
                        TextRenderer.DrawText(e.Graphics, asignacion.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, asignacion.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
            }
        }

        protected override void InitialLoad()
        {
            try
            {
                LoadNotasSalida();
                this.MaestroBindingSource.DataSource = AsignacionManager.Instancia.ListarPorTipo((int)PedidoType.Telefono);
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                OcultarColumnas();
                LoadDataGridView();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void LoadNotasSalida()
        {
            this.cmbNotaSalida.ValueMember = "IdNotaSalida";
            this.cmbNotaSalida.DisplayMember = "IdNotaSalida";
            this.cmbNotaSalida.DisplayColumnNames = "IdNotaSalida, Fecha";
            this.cmbNotaSalida.DataSource = NotaSalidaManager.Instancia.Listar();
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["Empleados"].Visible = false;
            this.dgvMaestro.Columns["Descripcion"].Visible = false;
            this.dgvMaestro.Columns["NotaSalida"].Visible = false;
            this.dgvMaestro.Columns["Tipo"].Visible = false;
            this.dgvMaestro.Columns["IdAsignacion"].HeaderText = "Asignación";
        }

        private void LoadDataGridView()
        {
            this.dgvDetalle.DataGridView.Rows.Clear();
            this.dgvDetalle.DataGridView.Columns.Clear();
            this.dgvDetalle.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Empleado";
            colummn.HeaderText = "Empleado";
            colummn.Width = 200;
            colummn.ColumnNext = 3;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Telefono";
            colummn.HeaderText = "Telefono";
            colummn.Width = 120;
            colummn.ReadOnly = true;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Cantidad";
            colummn.HeaderText = "Cantidad";
            colummn.Width = 80;
            colummn.ReadOnly = true;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Comentario";
            colummn.HeaderText = "Comentario";
            colummn.DataType = DataType.Default;
            colummn.ControlType = CustomControlType.TextBox;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            this.dgvDetalle.DataGridView.Columns["Comentario"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected override void EventoNuevo()
        {
            this.dtpFecha.Enabled = false;
            this.dtpFecha.Value = EmpresaManager.Instancia.Fecha();
            this.dtpFecha.Focus();
        }

        protected override void EventoEditar()
        {
            this.dtpFecha.Enabled = true;
            this.dtpFecha.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void LoadData(object obj)
        {
            Asignacion asignacion = obj as Asignacion;
            if (asignacion != null)
            {
                asignacion = AsignacionManager.Instancia.ObtenerPorID(asignacion.IdAsignacion);

                this.identificador = asignacion.IdAsignacion;
                this.dtpFecha.Value = asignacion.Fecha;
                this.cmbNotaSalida.SelectedValue = asignacion.NotaSalida.IdNotaSalida;
                this.txtDescripcion.Text = asignacion.Descripcion;

                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleAsignacion d in asignacion.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Empleados.ToString();
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Empleados.IdEmpleado;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = Convert.ToInt32(d.Cantidad);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[3].Value = d.Comentario;
                }
            }
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        AsignacionManager.Instancia.Registrar(GetAsignacion());
                        break;
                    case EstadoActual.Editar:
                        AsignacionManager.Instancia.Actualizar(GetAsignacion());
                        break;
                    case EstadoActual.Eliminar:
                        AsignacionManager.Instancia.Eliminar(Convert.ToInt32(this.identificador));
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
            return result;
        }

        private Asignacion GetAsignacion()
        {
            Asignacion asignacion = new Asignacion
            {
                IdAsignacion = Convert.ToInt32(this.identificador),
                Fecha = this.dtpFecha.Value,
                NotaSalida = new NotaSalida { IdNotaSalida = Convert.ToInt32(this.cmbNotaSalida.SelectedValue) },
                Empleados = new Empleados { IdEmpleado = Empresa.Usuario.IdEmpleado },
                Descripcion = this.txtDescripcion.Text,
                Tipo = (int)PedidoType.Telefono
            };
            foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    asignacion.Detalle.Add(new DetalleAsignacion
                    {
                        Empleados = new Empleados { IdEmpleado = Convert.ToInt16(row.Cells[0].Tag) },
                        Bien = new Bien { IdBien = Convert.ToInt32(row.Cells[1].Tag) },
                        Cantidad = Convert.ToDecimal(row.Cells[2].Value),
                        Comentario = row.Cells[3].Value.ToString()
                    });
                }
            }
            return asignacion;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[0].Tag == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[1].Tag == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[2].Value == null)
            {
                result = false;
            }
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.cmbNotaSalida.SelectedValue == null)
            {
                this.errValidator.SetError(this.cmbNotaSalida, "Seleccionar Nota Salida.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbNotaSalida, string.Empty);
            }
            if (this.dgvDetalle.DataGridView.Rows.Count == 0)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, "No existe Entregas para Registrar.");
                result = false;
            }
            return result;
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            LoadDataGridView();
            this.lblNotaSalida.Text = string.Empty;
            base.ClearControls();
        }

        #region Miembros de Observador

        public void Notificar(object mensaje)
        {
            LoadNotasSalida();
        }

        #endregion
    }
}
